<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        /* 保持原有样式不变 */
        body {
            background-color: #f8f9fa;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .card {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
        .card-header {
            background-color: #0d6efd;
            color: white;
            font-weight: bold;
            text-align: center;
        }
        .form-control:focus {
            border-color: #0d6efd;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
        .btn-primary {
            width: 100%;
        }
        .error-message {
            color: #dc3545;
            margin-top: 0.5rem;
            display: none;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 1rem;
        }
    </style>
</head>
<body>
<div class="container mt-5 flex-grow-1 d-flex flex-column justify-content-center">
    <div class="row justify-content-center">
        <div class="col-md-5">
            <div class="card">
                <div class="card-header">
                    <i class="fa fa-user-circle me-2"></i>用户登录
                </div>
                <div class="card-body">
                    <form id="loginForm" method="post" action="/login">
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">密码</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div id="errorMsg" class="error-message"></div>

                        <div class="loading" id="loadingIndicator">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">登录中...</span>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-primary" id="loginBtn">
                            <i class="fa fa-sign-in me-1"></i>登录
                        </button>
                    </form>
                    
                    <!-- 显示服务器端错误信息 -->
                    <div th:if="${error}" class="alert alert-danger mt-3" role="alert">
                        <span th:text="${error}"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 配置接口地址
    const LOGIN_API_URL = "/api/login"; // 登录接口，会转发到shadow-admin服务
    const DASHBOARD_API_URL = "/dashboard"; // 需要调用的dashboard接口

    // 获取DOM元素
    const loginForm = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const errorMsg = document.getElementById('errorMsg');
    const loginBtn = document.getElementById('loginBtn');
    const loadingIndicator = document.getElementById('loadingIndicator');

    // 显示错误信息
    function showError(message) {
        errorMsg.textContent = message;
        errorMsg.style.display = 'block';
    }

    // 隐藏错误信息
    function hideError() {
        errorMsg.textContent = '';
        errorMsg.style.display = 'none';
    }

    // 显示/隐藏加载状态
    function setLoading(isLoading) {
        if (isLoading) {
            loadingIndicator.style.display = 'block';
            loginBtn.disabled = true;
            loginBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 登录中...';
        } else {
            loadingIndicator.style.display = 'none';
            loginBtn.disabled = false;
            loginBtn.innerHTML = '<i class="fa fa-sign-in me-1"></i>登录';
        }
    }

    // 登录成功后调用dashboard接口
    async function callDashboardApi(token) {
        try {
            const response = await fetch(DASHBOARD_API_URL, {
                method: 'GET', // 根据实际接口需求调整请求方法
                headers: {
                    'Authorization': `Bearer ${token}`, // 携带登录成功的token
                    'Content-Type': 'application/json'
                },
                timeout: 10000
            });

            if (!response.ok) {
                throw new Error(`获取仪表盘数据失败: ${response.statusText}`);
            }

            // 解析dashboard接口返回的数据
            const dashboardData = await response.json();
            console.log('仪表盘数据获取成功:', dashboardData);

            // 这里可以根据接口返回的数据进行页面跳转或渲染
            // 例如: 如果需要跳转到dashboard页面
            window.location.href = 'dashboard.html'; // 假设有一个dashboard.html页面

            // 或者: 如果需要在当前页面渲染数据，可以留空并处理数据
            return dashboardData;
        } catch (error) {
            console.error('调用dashboard接口失败:', error);
            throw error; // 抛出错误让上层处理
        }
    }

    // 修改登录成功后的逻辑，支持两种登录方式
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        hideError();

        const username = usernameInput.value.trim();
        const password = passwordInput.value;

        if (!username || !password) {
            showError('请输入用户名和密码');
            return;
        }

        try {
            setLoading(true);

            // 1. 使用AJAX登录
            const loginResponse = await fetch(LOGIN_API_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            });

            if (!loginResponse.ok) {
                const errorResult = await loginResponse.json();
                throw new Error(errorResult.message || `登录失败: ${loginResponse.status}`);
            }

            const loginResult = await loginResponse.json();

            // 2. 验证登录响应
            if (!loginResult.Authorization) {
                throw new Error('登录响应缺少授权信息');
            }

            // 3. 保存完整的Authorization头（包含"Bearer "）
            const authHeader = loginResult.Authorization;
            localStorage.setItem('authHeader', authHeader);

            // 4. 调用/dashboard接口获取视图
            const dashboardResponse = await fetch(DASHBOARD_API_URL, {
                method: 'GET',
                headers: {
                    'Authorization': authHeader, // 使用完整的Authorization头
                    'Accept': 'text/html' // 明确要求HTML响应
                }
            });

            // 5. 处理视图响应
            if (!dashboardResponse.ok) {
                throw new Error(`获取仪表盘失败: ${dashboardResponse.status}`);
            }

            // 6. 获取HTML内容
            const dashboardHtml = await dashboardResponse.text();

            // 7. 替换当前页面内容
            document.open();
            document.write(dashboardHtml);
            document.close();

            // 8. 更新页面标题和URL
            document.title = "仪表盘";
            history.pushState({}, "仪表盘", DASHBOARD_API_URL);

        } catch (error) {
            showError(error.message || '登录过程发生错误，请重试');

            // 回退到表单登录
            console.log('尝试表单登录作为备选方案');
            const formData = new FormData();
            formData.append('username', username);
            formData.append('password', password);

            const formResponse = await fetch('/login', {
                method: 'POST',
                body: formData
            });

            if (formResponse.redirected) {
                window.location.href = formResponse.url;
            }
        } finally {
            setLoading(false);
        }
    });
</script>
</body>
</html>
